define(['app', 'js/directive/listTree', 'js/filter/filterPk', 'laydate', 'pagination', 'autocomplete', 'editor', 'filesaver', 'fileupload'], function(app) {
    'use strict';
    app.controller('Pk', function($scope, dataFactoryCRM, $q, Upload) {
        $scope.pks;
        $scope.userinfo; //登陆用户信息
        $scope.sector; //部门信息
        $scope.user; //用户信息
        $scope.sectorUser //部门、个人信息
        $scope.object; //目标对象信息
        $scope.keytype; //页面加载时显示当前key类型
        $scope.person; //设定目标的主体（人、部门）
        $scope.pktype; //PK类型
        $scope.time; //系统时间(由后台传出)
        $scope.pkRcode; //返回码
        $scope.pkMsg; //返回信息
        $scope.type = {
            a: '',
            b: ''
        };
        $scope.value = {
            key: '',
            search: '',
            type: ''
        };
        $scope.pkPages = {
            pageAll: 1,
            pageNow: 1,
            pageSize: $scope.psize,
            k: 3
        };
        /*系统错误调用*/
        $scope.msgAttention = function() {
            $('.ui.systemerror').modal({
                closable: true,
                onDeny: function() {
                    return true;
                },
                onApprove: function() {
                    $('.ui.dimmer.modals.page.transition.visible.active.dimmers').removeClass('dimmers');
                }
            }).modal('show');

            setTimeout(function() {
                var system = $('.ui.dimmer.modals.page.transition.visible.active');
                if (system) {
                    $('.ui.dimmer.modals.page.transition.visible.active').addClass('dimmers');
                }
            }, 1000);
        };
        /*获取登陆者信息*/
        $scope.userInfo = function() {
            var obj = new Function("return" + sessionStorage.user)();
            $scope.userinfo = obj;
            $scope.getObject();
        };
        /*获取目标对象*/
        $scope.getObject = function() {
            var _url = 'Goals/getObject?sector_id=' + $scope.userinfo.sector_id;
            dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
                if (_d.rcode) {
                    $scope.sector = _d.sector;
                    $scope.user = _d.user;
                    $scope.sectorUser = _d.sectorUser;
                }
            })
            $scope.Object();
        };
        $scope.Object = function() {
            if ($scope.value.type == 1) {
                $scope.object = $scope.user;
            } else if ($scope.value.type == 2) {
                $scope.object = $scope.sector;
            } else if ($scope.value.type == 3) {
                $scope.object = $scope.sectorUser;
            }
        };
        /*PK类型*/
        $scope.switchType = function(key) {
            if (key) {
                $scope.pktype = key;
            } else {
                $scope.pktype = 1;
            }
        };
        /*自动补全触发事件*/
        $scope.selecteAdda = function(selected) {
            if (selected) {
                $('#add_obja').val(selected.originalObject.id);
            }
        };
        $scope.selecteAddb = function(selected) {
            if (selected) {
                $('#add_objb').val(selected.originalObject.id);
            }
        };
        /**
         * 获取PK信息
         * 全部：key=0,type=？；进行中：key=1，type=？；已经结束：key=2,type=？；未开始：key=3,type=？；搜索：key=？type=？；部门：key=？，type=2；个人：key=？，type=1；
         */
        $scope.getpkList = function(key, type) {

            $scope.$emit("BUSY");
            if ($scope.value.key == '' && $scope.value.type == '') {
                $scope.value.key = 4;
                $scope.value.type = 2;
            } else {
                if (key != '' && key) {
                    $scope.value.key = key;
                }
                if (type != '' && type) {
                    $scope.value.type = type;
                }
            }
            var start_time = $('#search_time1').val();
            var end_time = $('#search_time2').val();
            if ($('#search_obj_value').val()) {
                var catcher = $('#search_obj_value').val();
            } else {
                var catcher = '';
            }
            var result = $("#search_state").val();
            if (result == 5) {
                result = '';
            }
            var _url = 'Pk/index?p=' + $scope.pkPages.pageNow + '&psize=' + $scope.psize + '&sector_id=' + $scope.userinfo.sector_id + '&key=' + $scope.value.key + '&type=' + $scope.value.type + '&start_time=' + start_time + '&end_time=' + end_time + '&catcher=' + catcher + '&result=' + result;
            dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
                if (_d.rcode) {
                    $scope.pkPages.pageSize = _d.psize;
                    $scope.pkPages.pageAll = _d.pall;
                    $scope.pkPages.pageNow = _d.p;
                    $scope.pks = _d.data;
                    $scope.time = _d.time.slice(0, 10);
                    var length = $scope.pks.length;
                    for (var i = 0; i < length; i++) {
                        var start_time = $scope.pks[i]['start_time'].slice(0, 10);
                        var end_time = $scope.pks[i]['end_time'].slice(0, 10);
                        if (end_time >= $scope.time) {
                            if (start_time > $scope.time) {
                                $scope.pks[i]['keytype'] = "未开始";
                            } else {
                                $scope.pks[i]['keytype'] = "进行中";
                            }
                        } else {
                            $scope.pks[i]['keytype'] = "已经结束";
                        }
                    }
                } else {
                    $scope.pks = '';
                    $scope.pkPages.pageAll = 0;
                }
                $scope.$emit("NOTBUSY");
            });
        };
        /*check radio与目标对象的二级联动*/
        $scope.checkRadio = function(key) {
            if (key == 1) {
                $scope.type.a = 1;
                $scope.object1 = $scope.user;
                $('#add_objecta_value').val('');
            } else if (key == 2) {
                $scope.type.a = 2;
                $scope.object1 = $scope.sector;
                $('#add_objecta_value').val('');
            } else if (key == 3) {
                $scope.person = 1;
            } else if (key == 4) {
                $scope.person = 2;
            } else if (key == 5) {
                $scope.type.b = 1;
                $scope.object2 = $scope.user;
                $('#add_objectb_value').val('');
            } else if (key == 6) {
                $scope.type.b = 2;
                $scope.object2 = $scope.sector;
                $('#add_objectb_value').val('');
            }
        };
        /*目标对象自动补全判断个人、部门选中状态*/
        $scope.checkManager = function(key) {
            if (key == 1) {
                var a = document.getElementsByName('frequency1');
                if (a[0].checked) {
                    if ($scope.object1 != $scope.user) {
                        $scope.object1 = $scope.user;
                    }
                } else if (a[1].checked) {
                    if ($scope.object1 != $scope.sector) {
                        $scope.object1 = $scope.sector;
                    }
                }
            } else if (key == 2) {
                var b = document.getElementsByName('frequency2');
                if (b[0].checked) {
                    if ($scope.object2 != $scope.user) {
                        $scope.object2 = $scope.user;
                    }
                } else if (b[1].checked) {
                    if ($scope.object2 != $scope.sector) {
                        $scope.object2 = $scope.sector;
                    }
                }
            }
        };
        /* 验证表单 */
        $scope.clickvalid = function(id) {
            if ($('#' + id).val() != '') {
                $('#' + id).removeClass('notvalid');
            }
        };
        /**导出PK */
        $scope.pkExport = function() {
            var start_time = $('#search_time1').val();
            var end_time = $('#search_time2').val();
            var result = $("#search_state").val();
            if (result == 5) {
                result = '';
            }
            var _url = 'Pk/pkExport?start_time=' + start_time + '&end_time=' + end_time + '&pk_res=' + result;
            var rand = Math.floor(1000 + Math.random() * (9999 - 1000));
            dataFactoryCRM.getDataByAPIS(_url).then(function(data) {
                var blob = new Blob([data], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                });
                saveAs(blob, '' + rand + '.xls');
            });
        };
        /**导入PK */
        $scope.uploadImg = '';
        //提交
        $scope.submit = function() {
            $scope.upload($scope.file);
        };
        $scope.upload = function(file) {
            $scope.$emit("BUSY");
            $scope.fileInfo = file;
            Upload.upload({
                //服务端接收
                url: '/index.php/Admin/Pk/pkImport',
                //上传的同时带的参数
                data: { 'p': $scope.pkPages.pageNow },
                //上传的文件
                file: file
            }).progress(function(evt) {
                //进度条
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progess:' + progressPercentage + '%' + evt.config.file.name);
            }).success(function(data, status, headers, config) {
                //上传成功
                // console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
                // $scope.uploadImg = data;
                if (!data.rcode) {
                    $scope.$emit("NOTBUSY");
                    $scope.pkRcode = 0;
                    var errorId = data.data;
                    var msg = '编号是:';
                    for (var key in errorId) {
                        if (key != (errorId.length - 1)) {
                            msg = msg + errorId[key] + '、';
                        } else {
                            msg = msg + errorId[key] + '的PK信息没有导入成功，请核查信息之后再次尝试或手动导入';
                        }
                    }
                    $scope.pkMsg = msg;
                    $scope.msgAttention();
                }
                $scope.file = '';
                $scope.$emit("NOTBUSY");
            }).error(function(data, status, headers, config) {
                //上传失败
                $scope.$emit("NOTBUSY");
                console.log('error status: ' + status);
            });
        };
        $scope.clickvalida = function() {};
        /* 增加PK */
        $scope.addShowPK = function() {
            $scope.object1 = $scope.user;
            $scope.object2 = $scope.user;
            $scope.person = 1;
            $('#frm-addPK input').val('');
            $('#frm-addPK textarea').val('');
            $('#add_obja_value').val('');
            $('#add_objb_value').val('');
            $('.ui .addPK').modal({
                onApprove: function() {
                    if ($('#frm-addPK').form('is valid')) {
                        if (!$scope.type.a) {
                            $scope.type.a = 1;
                        }
                        if (!$scope.type.b) {
                            $scope.type.b = 1;
                        }
                        var a_type = $scope.type.a;
                        var b_type = $scope.type.b;
                        var a = $('#add_obja').val();
                        var b = $('#add_objb').val();
                        var a_goal;
                        var b_goal;
                        if (!$scope.pktype) {
                            $scope.pktype = 1;
                        }
                        if ($scope.pktype == 1) {
                            a_goal = 0;
                            b_goal = 0;
                        } else if ($scope.pktype == 2) {
                            if ($('#frm-addPK input[name="goal_a"]').val()) {
                                a_goal = $('#frm-addPK input[name="goal_a"]').val();
                                b_goal = $('#frm-addPK input[name="goal_b"]').val();
                            } else {
                                a_goal = 0;
                                b_goal = 0;
                            }
                        } else if ($scope.pktype == 3) {
                            if ($scope.person == 1) {
                                a_goal = $('#frm-addPK input[name="goal"]').val();
                                b_goal = 0;
                            } else if ($scope.person == 2) {
                                a_goal = 0;
                                b_goal = $('#frm-addPK input[name="goal"]').val();
                            }
                        }
                        $scope.person = '';
                        if ($('#add_objecta_value').val() && $('#add_objectb_value').val() && $('#add_objecta_value').val() != $('#add_objectb_value').val() && $('#a_prize').val() && $('#b_prize').val()) {
                            var dad = $('#frm-addPK').serialize() + '&a_type=' + a_type + '&b_type=' + b_type + '&aname=' + a + '&bname=' + b + '&a_goal=' + a_goal + '&b_goal=' + b_goal + '&pk_type=' + $scope.pktype;
                            $scope.addPK(dad);
                            return true;
                        }
                    } else {
                        if ($('#a_prize').val() == '') {
                            $('#a_prize').addClass('notvalid');
                        }
                        if ($('#b_prize').val() == '') {
                            $('#b_prize').addClass('notvalid');
                        }
                        if ($('#add_obja').val() == '') {
                            $('#add_a').addClass('notvalid');
                        }
                        if ($('#add_objb').val() == '') {
                            $('#add_b').addClass('notvalid');
                        }
                        return false;
                    }
                }
            }).modal('show');
        };
        $scope.addPK = function(dad) {
            $scope.$emit("BUSY");
            $scope.busy = dataFactoryCRM.postDataByAPI('Pk/addPK', dad)
                .then(function(data) {
                    if (data.rcode == 1) {
                        $scope.getpkList('', '');
                    } else if (data.rcode == 2) {
                        $('.ui .nodel').modal('show');
                    }
                    $scope.$emit("NOTBUSY");
                })
        };
        /*查看PK*/
        $scope.lookPk = function() {
            var _vpks = this.vpk;
            $('#frm-lookPK p[name="start_time"]').text(_vpks.start_time);
            $('#frm-lookPK p[name="end_time"]').text(_vpks.end_time);
            $('#frm-lookPK p[name="a_object"]').text(_vpks.a_object);
            $('#frm-lookPK p[name="a_goal"]').text(_vpks.a_goal);
            $('#frm-lookPK p[name="b_object"]').text(_vpks.b_object);
            $('#frm-lookPK p[name="b_goal"]').text(_vpks.b_goal);
            $('#frm-lookPK p[name="b_prize"]').text(_vpks.b_prize);
            $('#frm-lookPK p[name="a_prize"]').text(_vpks.a_prize);
            $('#frm-lookPK p[name="info"]').text(_vpks.info);
            var pk_type;
            if (_vpks.pk_type == 1) {
                pk_type = '一较高下';
            } else if (_vpks.pk_type == 2) {
                pk_type = '达成目标';
            } else if (_vpks.pk_type == 3) {
                pk_type = '保证完成';
            }
            $('#frm-lookPK label[name="pk_type"]').text(pk_type);
            var result = _vpks.pk_res;
            if (result == 0) {
                result = '未处理';
            } else if (result == 1) {
                result = '正方胜出';
            } else if (result == 2) {
                result = '反方胜出';
            } else if (result == 3) {
                result = '都胜出';
            } else if (result == 4) {
                result = '都失败';
            }
            $('#frm-lookPK h3[name="pk_res"]').text(result);
            $('.ui .lookPK').modal('show');
        };
        /*编辑PK*/
        $scope.editShowPk = function() {
            var _vpks = this.vpk;
            $('#frm-editPK input[name="edit_a_goal"]').attr('disabled', false);
            $('#frm-editPK input[name="edit_b_goal"]').attr('disabled', false);
            $('#frm-editPK input[name="edit_start_time"]').val(_vpks.start_time);
            $('#frm-editPK input[name="edit_end_time"]').val(_vpks.end_time);
            $('#frm-editPK input[name="edit_a_goal"]').val(_vpks.a_goal);
            $('#frm-editPK input[name="edit_b_goal"]').val(_vpks.b_goal);
            $('#frm-editPK input[name="edit_b_prize"]').val(_vpks.b_prize);
            $('#frm-editPK input[name="edit_a_prize"]').val(_vpks.a_prize);
            $('#frm-editPK th[name="pka"]').text('A(正)方-' + _vpks.a_object);
            $('#frm-editPK th[name="pkb"]').text('B(反)方-' + _vpks.b_object);
            $('#frm-editPK textarea[name="edit_info"]').val(_vpks.info);
            var pk_type;
            if (_vpks.pk_type == 1) {
                pk_type = '一较高下';
            } else if (_vpks.pk_type == 2) {
                pk_type = '达成目标';
            } else if (_vpks.pk_type == 3) {
                pk_type = '保证完成';
            }
            $('#frm-editPK label[name="edit_pk_type"]').text(pk_type);
            // $('#frm-lookPK label[name="pk_type"]').text(pk_type);
            if (_vpks.a_goal == 0) {
                $('#frm-editPK input[name="edit_a_goal"]').attr('disabled', true);
            }
            if (_vpks.b_goal == 0) {
                $('#frm-editPK input[name="edit_b_goal"]').attr('disabled', true);
            }
            $('.ui .editPK').modal({
                onApprove: function() {
                    var da = $('#frm-editPK').serialize() + '&pkid=' + _vpks.pkid;
                    if ($('#frm-editPK').form('is valid')) {
                        $scope.editPK(da);
                        return true;
                    } else {
                        return false;
                    }
                }
            }).modal('show');
        };
        $scope.editPK = function(da) {
            $scope.$emit("BUSY");
            $scope.busy = dataFactoryCRM.postDataByAPI('Pk/editPK', da)
                .then(function(data) {
                    $scope.pkRcode = data.rcode;
                    if (data.rcode) {
                        $scope.getpkList('', '');
                    } else {
                        $scope.$emit("NOTBUSY");
                        $scope.pkMsg = data.msg;
                        $scope.msgAttention();
                    }
                    $scope.$emit("NOTBUSY");
                    $('#frm-editPK input').val('');
                    $('#frm-editPK textarea').val('');
                });
        };
        /*删除PK*/
        $scope.delShowPk = function() {
            var _vpks = this.vpk;
            $('#del-model .content p').html("确认删除" + _vpks.a_object + "和" + _vpks.b_object + "的 【PK信息】 吗？");
            $('.ui .del').modal({
                onApprove: function() {
                    $scope.$emit("BUSY");
                    dataFactoryCRM.getDataByAPI('Pk/delShowPk?pkid=' + _vpks.pkid)
                        .then(function(data) {
                            $scope.pkRcode = data.rcode;
                            if (data.rcode) {
                                $scope.getpkList('', '');
                            } else {
                                $scope.$emit("NOTBUSY");
                                $scope.pkMsg = data.msg;
                                $scope.msgAttention();
                            }
                            $scope.$emit("NOTBUSY");
                        });
                }
            }).modal('show');
        };
        /*标签页实现部门、个人切换*/
        $scope.first = function() {
            $scope.getpkList('', 2);
            $scope.Object();
        };
        $scope.second = function() {
            $scope.getpkList('', 1);
            $scope.Object();
        };
        $scope.third = function() {
            $scope.getpkList('', 3);
            $scope.Object();
        };
        /*页面自动加载*/
        $scope.autoLoading = function() {
            $scope.userInfo();
            $scope.getpkList('', '');
            // $scope.getMount();
            $scope.pktype = 1;
        };
        $scope.autoLoading();



        $scope.submitImage = function() {

            $scope.images.file1 = $scope.file1;
            $scope.images.file2 = $scope.file2;

            dataFactoryCRM.uploadBinaryFile($scope.images)
                .then(function(data) {
                    console.log(data);
                })
        }

    });

});